// pages/content/content.js
const req = require('../../utils/request.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type_id: null, // 1品牌2产品
    artLists: [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],//最新文章
    page_no: 1,
    page_size: 14,
    type_id: null,
    media_type: 0,
    datalist: null,
    percent: 0,
    showCover: false,
    showLoading: false,
    showLoadBig: false,
    ifCancelLoad: false,
    showAuth: false,
    noMore: false
  },

  checkOut(e) {
    let media_type = e.currentTarget.dataset.media_type;
    if (media_type != this.data.media_type) {
      this.setData({
        media_type: media_type,
        page_no: 1,
        datalist: null
      })
      this.getListDetail()
    }
  },
  toLookVideo(e){
    console.log(1)
    
    let par = e.currentTarget.dataset.item;
    // this.videoContext.requestFullScreen();
    wx.navigateTo({
      url: '/pages/content/video?name=' + par.media_remark +'&url='+par.url,
    })
    // this.videoContext.play();
  },

  toLoadDown(e) {
    let that = this
    that.setData({
      showCover: true,
      showLoadBig: true
    })

    // wx.showModal({
    //   title: '复制下列网址，使用点击即可 （大图可用于印刷海报）',
    //   content: 'https:pan.baidu.comdiskhomeallvmode',
    //   confirmText: '复制链接',
    //   confirmColor: '#F63B75',
    //   success(res) {
    //     if (res.confirm) {
    //       console.log('用户点击确定')
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
  },
  doCancel(e){
    let which = e.currentTarget.dataset.which;
    this.setData({
      [which]: false,
      showCover: false,
      percent: 0
    })
  },
  getListDetail(){
    let params = {
      page_no: this.data.page_no,
      page_size: this.data.page_size,
      type_id: this.data.type_id,
      media_type: this.data.media_type
    }
    req.getListDetail(params).then(res=>{
      console.log('res.data.data', res.data.data)
      if (res.data.data.length&&(res.data.data.length<this.data.page_size)){
        this.setData({
          noMore: true
        })
      }
      if(this.data.datalist){
        let data = this.data.datalist;
        data.push(...res.data.data);
        this.setData({
          datalist: data
        })
      }else{
        this.setData({
          datalist: res.data.data
        })
      }
      
    })
  },
  cancelLoad(){
    this.setData({
      ifCancelLoad: true
    })
  },
  loadAll(e){
    let self = this;

    wx.getSetting({
      success(res) {
        console.log('---------',res.authSetting)
        // res.authSetting = {
        //   "scope.userInfo": true,
        //   "scope.userLocation": true
        // }
        if (!res['scope.writePhotosAlbum']){
          console.log(123123)
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success(res) {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              console.log(res, '111')
              if (self.data.datalist && self.data.datalist.length){
                self.setData({
                  ifCancelLoad: false
                })
                wx.showModal({
                  title: '',
                  content: '是否全部下载到相册',
                  confirmText: '是',
                  confirmColor: '#F63B75',
                  success(res) {
                    if (res.confirm) {
                      // debugger
                      self.setData({
                        percent: 0,
                        showCover: true,
                        showLoading: true
                      })
                      console.log('----',self.data.showCover)
                      // debugger
                      try {
                          var index = 0
                          self.download(index)
                      } catch (e) {
                        console.log(11111111111111111111111111111111111111)
                        if (e.message != "EndIterative") {
                          console.log(11111111111111111111111111111111111111)
                          throw e;
                        }
                      }

                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })



              }else{
                wx.showModal({
                  // title: '温馨提示',
                  showCancel: false,
                  content: '暂无下载资源哦！',
                })
              }
            },
            fail(err) {
              console.log(888888)
              console.log(err)
              self.setData({
                showCover: true,
                showAuth: true
              })
              // wx.openSetting({
              //   success(res) {
              //     console.log(res.authSetting)
              //   }
              // })
            },
            complete(res){
              // console.log(res)
            }
          })
        }else{
          console.log(9999999)
        }
      }
    })



      
      
    
  },
  download(index){
    let self = this;
    if (self.data.ifCancelLoad) {
      self.setData({
        percent: 0,
        showCover: false,
        showLoading: false
      })
      console.log('99999999999999999999')
      // break;
      return false
    }
    wx.downloadFile({
      url: self.data.datalist[index].url, //仅为示例，并非真实的资源
      success(res) {
        console.log(res);
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          if (self.data.media_type == 0) {
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success(res) {
                console.log(res)
                self.setData({
                  percent: Math.ceil((index + 1) / self.data.datalist.length) * 100
                })

              },
              complete(err) {
                console.log(err)
                // if (index == self.data.datalist.length - 1) {
                //   self.setData({
                //     percent: 0,
                //     showCover: false,
                //     showLoading: false
                //   })
                //   if (err.errMsg == 'saveVideoToPhotosAlbum:ok') {
                //     wx.showModal({
                //       title: '',
                //       showCancel: false,
                //       content: '下载完成',
                //     })
                //   } else {
                //     wx.showModal({
                //       title: '',
                //       content: '下载停止!',
                //     })
                //   }

                // }

                if (index == self.data.datalist.length - 1) {
                  self.setData({
                    percent: 0,
                    showCover: false,
                    showLoading: false
                  })
                  if (err.errMsg == 'saveImageToPhotosAlbum:ok') {
                    wx.showToast({
                      title: '下载完成',
                      icon: 'success',
                      duration: 1000
                    })
                  } else {
                    if (self.data.ifCancelLoad){
                      // wx.showModal({
                      //   title: '',
                      //   showCancel: false,
                      //   content: '下载完成!',
                      // })
                      wx.showToast({
                        title: '已取消',
                        icon: 'none',
                        duration: 1000
                      })
                    }else{
                      // wx.showModal({
                      //   title: '',
                      //   showCancel: false,
                      //   content: '下载停止!',
                      // })
                      wx.showToast({
                        title: '下载停止',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                    
                  }

                }
                if (index < self.data.datalist.length - 1) {
                  index += 1;
                  self.download(index)
                }


              }
            })
          } else {
            wx.saveVideoToPhotosAlbum({
              filePath: res.tempFilePath,
              success(res) {
                self.setData({
                  percent: Math.ceil((index + 1) / self.data.datalist.length) * 100
                })
              },
              complete(err) {
                console.log(err)
                if (index == self.data.datalist.length - 1) {
                  self.setData({
                    percent: 0,
                    showCover: false,
                    showLoading: false
                  })
                  if (err.errMsg == 'saveVideoToPhotosAlbum:ok') {
                    // wx.showModal({
                    //   title: '',
                    //   showCancel: false,
                    //   content: '下载完成',
                    // })
                    wx.showToast({
                      title: '下载完成',
                      icon: 'success',
                      duration: 1000
                    })
                  } else {
                    wx.showToast({
                      title: '下载完成',
                      icon: 'success',
                      duration: 1000
                    })
                  }

                }
                if(index<self.data.datalist.length-1){
                  index += 1;
                  self.download(index)
                }
                

              }
            })
          }

        }
      }
    })
  },
  copyLink(){
    wx.setClipboardData({
      data: 'https://pan.baidu.com/s/1MfJ_EY6PL3tUg5rvxg66_Q',
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },
  cancelAuth(){
    this.setData({
      showCover: false,
      showAuth: false
    })
  },
  toLookDetail(e){
    let item = e.currentTarget.dataset.item
    console.log(item)
    let data = this.data.datalist;
    var arr = []
    data.forEach(item=>{
      arr.push(item.url)
    })
    wx.previewImage({
      current: item, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },
  inits(){
    this.getListDetail()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      type_id: options.type_id
    })
    this.inits()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.videoContext = wx.createVideoContext('myVideo');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if(this.data.showAuth){
      this.setData({
        showCover: false,
        showAuth: false
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      page_no: parseInt(this.data.page_no) + 1
    })
    this.getListDetail();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.shareInfo.title,
      imageUrl: app.globalData.shareInfo.imageUrl
    }
  }
})